<template>
  <div>
    <el-card class="box-card" style="margin-bottom:1%;">
        <div slot="header" class="clearfix">
          <span>试卷基础信息</span>
        </div>
        <el-form ref="addBaseData"  :rules="rules" :model="addBaseData" label-width="140px">
          <el-row>
            <el-col :span="8">
              <el-form-item label="试卷名称" prop="name">
                <el-input v-model="addBaseData.name"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="考试起始时间" prop="startTime">
                <input type="hidden" v-model="addBaseData.startTime = SeTime[0]">
                <input type="hidden" v-model="addBaseData.endTime = SeTime[1]">
                <el-date-picker
                  v-model="SeTime"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="考试时长" prop="lengthOfTime">
                <el-input v-model="addBaseData.lengthOfTime"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="8">
              <el-form-item label="及格百分比(%)" prop="passPercentage">
                <el-input v-model="addBaseData.passPercentage"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="试卷描述" prop="description">
                <el-input  type="textarea" v-model="addBaseData.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>
      <el-card class="box-card padding" style="margin-bottom:1%;">
          <div slot="header" class="clearfix">
            <span>试题信息</span>
            <div class="btn-box">
              <el-form label-width="140px" :rules="rules" class="formSelect">
                <el-form-item label="试卷类型">
                  <el-select v-model="testType" placeholder="请选择试卷类型" class="tree-select">
                    <el-option
                      v-for="item in testTypeList"
                      :key="item.paramValue"
                      :label="item.paramName"
                      :value="item.paramValue">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-form>
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit-outline"
                @click="addSearchCondition" style="position:relative;margin-right:20px">新增试题</el-button>
              <el-button  type="primary"  icon="el-icon-plus"  style=""   @click="submitForm()">保 存</el-button>
            </div>
          </div>
          <div class="testBox">
            <el-row  v-for="(item,index) in liList" :key="item.id" class="addRow"  :gutter="20">
              <el-form  :rules="rules" label-position="top"  :model="liList[index]" :ref="liList[index]">
                <el-col class="selectWidth">
                  <el-form-item prop="indexTypeKey" label="题目类型" >
                    <el-select v-model="liList[index].type" disabled :label="liList[index].type" placeholder="题目类型" class="tree-select">
                      <el-option
                        v-for="item in testTypeList"
                        :key="item.paramValue"
                        :label="item.paramName"
                        :value="item.paramValue">
                      </el-option>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="2">
                  <el-form-item  prop="no" label="题目编号">
                    <el-input  v-model="liList[index].no" placeholder="请输入题号"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item  prop="description" label="题目名称">
                    <el-input type="textarea" v-model="liList[index].description" placeholder="请输入题目"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item  prop="score" label="题目分值">
                    <el-input v-model="liList[index].score"  placeholder="请输入分值"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4">
                  <el-form-item prop="trueAnswer" label="正确答案">
                    <el-input v-model="liList[index].trueAnswer" placeholder="正确答案" readonly></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="4" center>
                  <el-button
                    size="mini"
                    icon="el-icon-delete"
                    type="danger"
                    @click="removeSearchCondition(index)" class="delBtns">删除试题</el-button>
                </el-col>
                <el-row v-for="(items,indexs) in liList[index].answers" :key="items.id" class="answerSpan" :gutter="20">
                  <el-col :span="2" class="answerNo">
                    <el-form-item>
                      <el-input readonly v-model="liList[index].answers[indexs].answersNo" placeholder="答案编号"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="answerValue">
                    <el-form-item>
                      <el-input v-model="liList[index].answers[indexs].answerValue" placeholder="请输入答案"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="trueAnswer">
                    <el-form-item>
                      <el-radio v-if="liList[index].type !=='00B'" v-model="liList[index].trueAnswer" :label="liList[index].answers[indexs].answersNo"></el-radio>
                      <el-checkbox-group v-if="liList[index].type==='00B'" v-model="liList[index].checked" size="mini">
                        <el-checkbox    @change="checkTrue(index)" :label="liList[index].answers[indexs].answersNo"></el-checkbox>
                      </el-checkbox-group>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8" class="answerBtn" center>
                    <el-button
                      size="mini"
                      icon="el-icon-edit-outline"
                      v-if="liList[index].type !=='00C'"
                      @click="addAnswer(index,indexs)" class="delBtns">新增答案</el-button>
                    <el-button
                    size="mini"
                    icon="el-icon-delete"
                    type="danger"
                    v-if="indexs > 1"
                    @click="removeAnswer(index,indexs)" class="delBtns">删除答案</el-button>
                  </el-col>
                </el-row>
              </el-form>
            </el-row>
          </div>
      </el-card>
  </div>
</template>
<script>
import { saveTest } from '@/api/examManagement/examPaper'
import { isvalidNumber, isvalidRequire } from '@/utils/validate'
// 非空
var validateRequire = (rule, value, callback) => {
  if (!isvalidRequire(value)) {
    callback(new Error('请输入必填项'))
  } else {
    callback()
  }
}
// 数字验证
var validNumber = (rule, value, callback) => {
  if (!isvalidNumber(value)) {
    callback(new Error('只能输入大于0的数字'))
  } else {
    callback()
  }
}
// 及格百分比不能大于100
var validLength = (rule, value, callback) => {
  if (parseInt(value) > 100) {
    callback(new Error('及格百分比不能大于100'))
  } else {
    callback()
  }
}
export default {
  props: {
    testTypeList: {
      type: Array,
      default: []
    },
    detailData: {
      type: Object,
      default: {}
    }
  },
  data() {
    return {
      addBaseData: {
        id: '',
        name: '',
        description: '',
        startTime: '',
        endTime: '',
        lengthOfTime: '',
        passPercentage: '',
        questionJson: {
          data: []
        }
      },
      testType: '',
      SeTime: [],
      rules: {
        name: [
          { required: true, message: '请输入试卷名称' },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        startTime: [
          { required: true, message: '请选择考试起止时间' }
        ],
        lengthOfTime: [
          { required: true, message: '请输入考试时长' },
          { trigger: 'blur', validator: validNumber }
        ],
        passPercentage: [
          { required: true, message: '请输入考试及格百分比' },
          { trigger: 'blur', validator: validLength },
          { trigger: 'blur', validator: validNumber }
        ],
        description: [
          { required: true, message: '请输入试卷描述' },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        question: [
          { required: true, message: '请输入题目' },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        no: [
          { required: true, message: '请输入题号' },
          { trigger: 'blur', validator: validNumber }
        ],
        score: [
          { required: true, message: '请输入分值' },
          { trigger: 'blur', validator: validNumber }
        ],
        trueAnswer: [
          { required: true, message: '请输入正确答案' },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        answerNo: [
          {
            required: true, message: '请输入答案编号'
          },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ],
        answerValue: [
          {
            required: true, message: '请输入答案'
          },
          { message: '数据不能包含特殊字符', validator: validateRequire }
        ]
      },
      codes: [],
      validateFlag: false,
      liList: [] // 单选题
    }
  },
  watch: {
    detailData: function() {
      this.generateBig_1()
      if (JSON.stringify(this.detailData) !== '{}') {
        this.addBaseData = {
          id: this.detailData.entity.id,
          name: this.detailData.entity.name,
          description: this.detailData.entity.description,
          startTime: this.detailData.entity.startTime,
          endTime: this.detailData.entity.endTime,
          lengthOfTime: this.detailData.entity.lengthOfTime,
          passPercentage: this.detailData.entity.passPercentage
        }
        this.SeTime = [this.detailData.entity.startTime, this.detailData.entity.endTime]
        this.detailData.questions.forEach(element => {
          element.answers = JSON.parse(element.answers)
        })
        this.liList = this.detailData.questions
        this.liList.forEach(items => {
          if (items.type === '00B') {
            items.checked = []
            items.checked = items.trueAnswer.split('')
          }
        })
      } else {
        this.$refs['addBaseData'].resetFields()
        this.addBaseData = {
          id: '',
          name: '',
          description: '',
          startTime: '',
          endTime: '',
          lengthOfTime: '',
          passPercentage: '',
          questionJson: {
            data: []
          }
        }
        this.SeTime = []
        this.liList = []
      }
    }
  },
  methods: {
    generateBig_1() {
      for (var i = 65; i < 91; i++) {
        this.codes.push(String.fromCharCode(i))
      }
    },
    checkTrue(index) {
      this.liList[index].trueAnswer = this.liList[index].checked.sort().join('')
    },
    submitForm() {
      this.$refs['addBaseData'].validate((valid) => {
        if (valid) {
          this.validateAddForm()
        } else {
          this.validateFlag = false
          console.log('error submit!!')
          return false
        }
      })
    },
    validateAddForm() {
      if (this.$refs[Object()] !== undefined) {
        if (this.$refs[Object()].length !== 0) {
          for (const index in this.$refs[Object()]) {
            this.$refs[Object()][index].validate((valid) => {
              if (valid) {
              // this.saveCircle()
                this.validateFlag = true
              } else {
                this.validateFlag = false
              }
            })
            if (!this.validateFlag) {
              break
            }
          }
          if (this.validateFlag) {
            this.saveCircle()
          }
        } else {
          this.saveCircle()
        }
      } else {
        this.saveCircle()
      }
    },
    saveCircle() {
      if (this.liList.length !== 0) {
        this.addBaseData.questionJson = {
          data: [
            {
              no: '',
              description: '',
              answers: [{
                answersNo: '',
                answerValue: ''
              }, {
                answersNo: '',
                answerValue: ''
              }],
              trueAnswer: '',
              type: this.testType,
              score: ''
            }
          ]
        }
        for (var list in this.liList) {
          for (var i in this.liList[list].answers) {
            for (var key in this.liList[list].answers[i]) {
              if (this.liList[list].answers[i][key] !== '0' && !this.liList[list].answers[i][key]) {
                this.validateFlag = false
                break
              } else {
                this.validateFlag = true
              }
            }
          }
          if (this.validateFlag) {
            JSON.stringify(this.liList[list].answers)
          } else {
            this.$message({
              message: '有答案编号或者答案未填写，请完整填写',
              type: 'warning'
            })
            break
          }
        }
        if (this.validateFlag) {
          this.$emit('loadingShow')
          this.addBaseData.questionJson.data = this.liList
          this.addBaseData.questionJson = JSON.stringify(this.addBaseData.questionJson)
          saveTest(this.addBaseData).then(response => {
            this.$emit('savaSuccess')
            this.addBaseData.questionJson = {
              data: []
            }
          }).catch(error => {
            this.addBaseData.questionJson = JSON.parse(this.addBaseData.questionJson)
            this.$emit('loadingHide')
            console.log(error)
          })
        }
      } else {
        this.$emit('loadingShow')
        saveTest(this.addBaseData).then(response => {
          this.$emit('savaSuccess')
        }).catch(error => {
          this.$emit('loadingHide')
          console.log(error)
        })
      }
    },
    addSearchCondition() {
      if (this.testType) {
        this.liList.unshift({
          no: '',
          description: '',
          answers: [{
            answersNo: 'A',
            answerValue: ''
          }, {
            answersNo: 'B',
            answerValue: ''
          }],
          type: this.testType,
          score: '',
          checked: []
        })
      } else {
        this.$message({
          message: '请先选择题目类型',
          type: 'warning'
        })
      }
    },
    addAnswer(index, indexs) {
      this.liList[index].answers.push(
        {
          answersNo: this.codes[this.liList[index].answers.length],
          answerValue: ''
        }
      )
    },
    removeAnswer(index, indexs) { // 搜索里面的删除搜索项
      this.liList[index].answers.splice(indexs, 1)
      for (var item in this.liList[index].answers) {
        this.liList[index].answers[item].answersNo = this.codes[item]
      }
      this.liList[index].trueAnswer = ''
      this.liList[index].checked = []
    },
    removeSearchCondition(index) { // 搜索里面的删除搜索项
      this.liList.splice(index, 1)
    }
  }
}
</script>
<style lang="scss" scoped>

 .tree-select,.el-date-editor,.el-textarea{width: 95%;}
 .el-input{width: 95%;}
 .delBtns{position: relative;left:5%;top:5px;}
.num{font-size: 18px;font-style: normal;font-weight: 700;}


  .el-input.is-disabled .el-input__inner{background: transparent;border:none;}
.el-input.is-disabled .el-input__icon{display: none;}
.selectWidth{width: 80px;}
  .formSelect{position: absolute;width: 300px;right:250px;}
  .header{position: relative;}
  .padding .el-card__header div{position: relative;}
  .padding .el-card__header .btn-box{position: absolute;right:0;top:50%;transform: translate(0 ,-50%)}

  .answerNo{width: 90px !important;}
  .answerValue{width: 60% !important;}
  .answerSpan{display:block;width:100%;height:60px;float: left;}
  .answerBtn{width: 25% !important;}
  .trueAnswer{width: 4% !important;}
  .trueAnswer .el-radio__label{display:none !important;}
  .trueAnswer  .el-form-item{position: relative;top:12px;}
</style>
